<?php
/**
 *
+------------------------------------+
| Author: amamatthew                 |
+------------------------------------+
 * 日    期：2017-08-06
 * 版    本：1.0.0
 * 功能说明：cURL工具类。
 **/
namespace app\ux;

class UtilCurl
{

    const DEFAULT_TIMEOUT = 30; //最大超时

    private $url;               //请求地址
    private $base_url = null;   //基地址

    private $curlError = false; //错误标记
    private $curlErrorCode = 0; //错误代码
    private $curlErrorMessage = null; //错误信息

    /**
     * Construct
     *
     * @access public
     * @param  $base_url
     * @throws \ErrorException
     */
    public function __construct($base_url = null)
    {
        if (!extension_loaded('curl')) {
            throw new \ErrorException('cURL library is not loaded');
        }

        $this->setUrl($base_url);
    }
    /**
     * Set Url
     *
     * @param  $url
     * @param  $mixed_data
     */
    public function setUrl($url)
    {
        $this->base_url = $url;
    }
    /**
     * get()
     *
     * @param string url 目标网址
     * @return string    返回内容
     */
    public function get($url = null)
    {

        $ch = curl_init();

        $this->url = !empty($url) ? $url : (!empty($this->base_url) ? $this->base_url : "");

        curl_setopt($ch, CURLOPT_URL, $this->url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, self::DEFAULT_TIMEOUT);

        $res = curl_exec($ch);

        //返回错误代码
        //
        if (curl_errno($ch)) {

            $this->curlErrorMessage = "cURL Error:" . curl_error($ch);
            $this->curlErrorCode = curl_errno($ch);
            $this->curlError = true;

            curl_close($ch);

            $result = array(
                "code" => $this->curlErrorCode,
                "msg"  => $this->curlErrorMessage,
                "data" => $url,
            );
            return (json_encode($result, JSON_UNESCAPED_UNICODE));
        }

        //关闭句柄，返回请求结果
        //
        curl_close($ch);
        return $res;
    }
}
